package com.liu.test.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liu.test.common.BaseContext;
import com.liu.test.common.ObjectRestResponse;
import com.liu.test.dto.GoodWithNum;
import com.liu.test.entity.*;
import com.liu.test.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping
@CrossOrigin
public class ShoppingCarController {
    @Autowired
    private LdrGoodsService goodsService;
    @Autowired
    private LdrUserService userService;
    @Autowired
    private LdrShoppingCarService shoppingCarService;
    @Autowired
    private LdrOrderService orderService;
    @Autowired
    private LdrFinalOrderService finalOrderService;


    @GetMapping("/getAllGoods")
    public ObjectRestResponse<List<LdrGoods>> getCarInfo() {
        List<LdrGoods> goods = goodsService.getAllGoods();
        ObjectRestResponse<List<LdrGoods>> result = new ObjectRestResponse<>();
        result.data(goods);
        return result;
    }

    //登录成功获取用户信息
    @GetMapping("/getUser")
    public ObjectRestResponse<LdrUser> getUser() {
        LdrUser user = userService.getUserInfo();
        BaseContext.setUserId(user.getUserId());
        ObjectRestResponse<LdrUser> result = new ObjectRestResponse<>();
        result.data(user);
        return result;
    }

    //添加进购物车，按一次加入购物车，商品数量+
    @PostMapping("/add")
    public ObjectRestResponse<LdrShoppingCar> add(@RequestBody LdrShoppingCar ldrShoppingCar) {
        String userId = "123456789";//BaseContext.getUserId();
        int goodId = ldrShoppingCar.getGoodId();
        ldrShoppingCar.setUserId(userId);
        LambdaQueryWrapper<LdrShoppingCar> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LdrShoppingCar::getUserId, userId);
        queryWrapper.eq(LdrShoppingCar::getGoodId, goodId);
        LdrShoppingCar car = shoppingCarService.getOne(queryWrapper);
        boolean isAdd;
        if (car == null) {//购物车里尚且没有当前商品，直接插入数据库
            car = new LdrShoppingCar();
            log.info("购物车里尚且没有当前商品，直接插入数据库");
            String carId = UUID.randomUUID().toString();
            log.info("UUID:" + carId);
            ldrShoppingCar.setCarId(carId);
            isAdd = shoppingCarService.save(ldrShoppingCar);
            BeanUtils.copyProperties(ldrShoppingCar, car);
            log.info("插入成功");
        } else {//购物车里已经有当前商品了，则数量+goodSum
            car.setGoodSum(car.getGoodSum() + ldrShoppingCar.getGoodSum());
            System.out.println(car.getCarId());
            System.out.println(car.getUserId());
            System.out.println(car.getGoodId());
            System.out.println(car.getGoodSum());
            log.info("购物车里已经有当前商品了，则数量+goodSum");
            isAdd = shoppingCarService.updateById(car);
            log.info("更新成功");
        }
        ObjectRestResponse<LdrShoppingCar> result = new ObjectRestResponse<>();
        result = isAdd ? result.data(car).message("加入购物车成功") : result.data(car).message("加入购物车失败");
        return result;
    }


    @GetMapping("/getMyCar")
    public ObjectRestResponse<List<GoodWithNum>> getMyCar() {
        LambdaQueryWrapper<LdrShoppingCar> queryWrapper = new LambdaQueryWrapper<>();
        String userId = "123456789";
        //userId = BaseContext.getUserId();
        queryWrapper.eq(LdrShoppingCar::getUserId, userId);
        List<LdrShoppingCar> myCarList = shoppingCarService.list(queryWrapper);

        //将数据封装到dto中
        List<GoodWithNum> goodWithNumList = myCarList.stream().map(item -> {
            //这是一个包含了LdrGoods数据以及商品数量num的对象
            GoodWithNum goodWithNum = new GoodWithNum();
            LdrGoods goods;
            LambdaQueryWrapper<LdrGoods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsLambdaQueryWrapper.eq(LdrGoods::getGoodId, item.getGoodId());
            goods = goodsService.getOne(goodsLambdaQueryWrapper);
            goodWithNum.setLdrGoods(goods);
            goodWithNum.setNum(item.getGoodSum());

            return goodWithNum;
        }).collect(Collectors.toList());
        ObjectRestResponse<List<GoodWithNum>> result = new ObjectRestResponse<>();
        return result.data(goodWithNumList);
    }

    //确认购物车，将购物车中所提交的商品写入数据库
    @PostMapping("/confirmOrder")
    public ObjectRestResponse<List<LdrOrder>> confirm(@RequestBody List<LdrOrder> orderList) {
//        String userId = BaseContext.getUserId();
        String userId = "123456789";
        String orderId = UUID.randomUUID().toString();
        double sumOfPrice = 0;

        List<LdrOrder> resultList = orderList.stream().map(item -> {
            LambdaQueryWrapper<LdrGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LdrGoods::getGoodId, item.getGoodId());
            //通过goodId查询到商品信息
            LdrGoods good = goodsService.getOne(queryWrapper);
            LdrOrder order = new LdrOrder();
            BeanUtils.copyProperties(item, order);
            order.setOrderId(orderId);
            order.setUserId(userId);
            order.setNumber(item.getNumber());
            order.setGoodPrice(good.getGoodPrice());


            return order;
        }).collect(Collectors.toList());
        for (LdrOrder ldrOrder : resultList) {
            sumOfPrice += ldrOrder.getGoodPrice() * ldrOrder.getNumber();
        }
        orderService.saveBatch(resultList);
        ObjectRestResponse<List<LdrOrder>> result = new ObjectRestResponse<>();
        result.data(resultList).message("购物车提交成功");

        //提交成功后应当将当前用户的购物车清空，或者清除已选中的提交的商品
        for (LdrOrder ldrOrder : resultList) {
            LambdaQueryWrapper<LdrShoppingCar> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LdrShoppingCar::getUserId,userId).eq(LdrShoppingCar::getGoodId,ldrOrder.getGoodId());
            shoppingCarService.remove(queryWrapper);
        }


        LdrFinalOrder finalOrder1 = finalOrderService.getById(orderId);
        LdrFinalOrder finalOrder = new LdrFinalOrder();
        finalOrder.setFinalOrderId(orderId);
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        finalOrder.setCreateTime(dateFormat.format(date));
        finalOrder.setSumOfPrice(sumOfPrice);
        if (finalOrder1 == null) {
            finalOrderService.save(finalOrder);
        } else {
            finalOrderService.updateById(finalOrder);

        }

        return result;
    }


    //移出购物车
    @PostMapping("/deleteGood")
    public ObjectRestResponse<LdrGoods> deleteGood(@RequestBody LdrGoods good) {
        String userId = "123456789";//BaseContext.getUserId();
        int goodId = good.getGoodId();
        LambdaQueryWrapper<LdrShoppingCar> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LdrShoppingCar::getGoodId, goodId);

        queryWrapper.eq(LdrShoppingCar::getUserId, userId);
        boolean isRemove = shoppingCarService.remove(queryWrapper);
        ObjectRestResponse<LdrGoods> result = new ObjectRestResponse<>();
        result.data(goodsService.getOne(new LambdaQueryWrapper<LdrGoods>().eq(LdrGoods::getGoodId, goodId)));
        result = isRemove ? result.message("移出购物车成功") : result.message("移出购物车失败");
        return result;
    }


}
